package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.adapter.NewpersonAdapter;
import com.luoxiang.socialandroid.adapter.OnlineAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.THost;
import com.luoxiang.socialandroid.bean.Typehost2Bean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class NewFragment extends LazyLoadFragment {
    private RecyclerView rc_new;
    private String token;
    private NewpersonAdapter adapter;
    private SmartRefreshLayout smartRefreshLayout;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private List<THost> list;
    private int page = 1;//是我们的页数

    @Override
    protected int setContentView() {
        return R.layout.fragment_new;
    }

    @Override
    protected void initView() {
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        rc_new = findViewById(R.id.rc_new);
        list = new ArrayList<>();
        smartRefreshLayout = findViewById(R.id.smartRefresh);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        rc_new.setLayoutManager(gridLayoutManager);
        adapter = new NewpersonAdapter();
        rc_new.setAdapter(adapter);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getTypeHosts(token, EXTRA, "2", page, "10");
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getTypeHosts(token, EXTRA, "2", page, "10");
            }
        });
    }

    @Override
    protected void lazyLoad() {
        getTypeHosts(token, EXTRA, "2", page, "10");
    }

    private void getTypeHosts(String token, String extra, String i, int page, String limit) {
        getRequest();
        NetUtils2.getInstance().getApiService().getTypeHosts2(token, extra, i, page, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr100", decryptStr);
                            Gson gson = new Gson();
                            Typehost2Bean bean = gson.fromJson(decryptStr, Typehost2Bean.class);


                            if (list != null) {
                                if (page == 1) {
                                    list.clear();
                                }
                            }
                            adapter.setOnAddClickListener(new OnlineAdapter.OnAddClickListener() {
                                @Override
                                public void onItemClicks(int userid) {
                                    Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                    intent.putExtra("userid", userid);
                                    startActivity(intent);
                                }
                            });

                            if (bean.getData() != null && bean.getData().getHosts() != null && bean.getData().getHosts().size() > 0) {

                                if (list != null) {
                                    list.addAll(bean.getData().getHosts());
                                }
                                adapter.setData(list);
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUtils.showShort(R.string.mi_wugengduoshuju);
                            }

                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}